<?php
/**
 * Created by JetBrains PhpStorm.
 * User: shaoshuai
 * Date: 12-7-14
 * Time: 下午9:35
 * To change this template use File | Settings | File Templates.
 */
class Chessboard
{
    /**
     * @var array
     */
    protected $matrix;

    /**
     * @var array
     */
    protected $airplanes;

    /**
     * 棋盘上飞机的坠毁坐标
     * @var array
     */
    protected $crashCoordinates;

    /**
     * @var array
     */
    protected $gameOverCountArray;

    /**
     * 棋盘类
     */
    public function __construct()
    {
        $this->airplanes = array();
        $this->initMatrix();
        $this->crashCoordinates = array();
        $this->gameOverCountArray = array();
    }

    /**
     * 初始化内置矩阵
     */
    protected function initMatrix()
    {
        $this->matrix = array();
        for ($i = 0; $i < 10; $i++) {
            array_push($this->matrix, array_pad(array(), 10, 0));
        }
    }

    /**
     * 向棋盘摆放一架飞机
     * @param Airplane $airplane
     * @param array $coordinate
     * @return Chessboard
     */
    public function addAirplane($airplane, $coordinate)
    {
        $crashCoordinate = $airplane->getCrashCoordinate();
        $crashCoordinate[0] += $coordinate['x'];
        $crashCoordinate[1] += $coordinate['y'];
        array_push($this->airplanes, $airplane);
        array_push($this->crashCoordinates, $crashCoordinate);
        array_push($this->gameOverCountArray, $crashCoordinate);
        Matrix::add($this->matrix, $airplane->getMatrix(), $coordinate);
        return $this;
    }

    public function isInCrashCoordinate($x, $y)
    {
        $in = false;
        foreach ($this->crashCoordinates as $coordinate) {
            if ($coordinate[0] == $x && $coordinate[1] == $y) {
                $in = true;
                break;
            }
        }
        return $in;
    }

    public function removeFromGameOverCountArray($x, $y)
    {
        $in = false;
        foreach ($this->gameOverCountArray as $key => $coordinate) {
            if ($coordinate[0] == $x && $coordinate[1] == $y) {
                $in = true;
                unset($this->gameOverCountArray[$key]);
                break;
            }
        }
        return $in;
    }

    /**
     * @param int $x
     * @param int $y
     * @return int
     */
    public function onFire($x, $y)
    {
        //1. not hit 2. hit 3. crash
        Functions::log($this->crashCoordinates);
        $status = 1;
        if ($this->isInCrashCoordinate($x, $y)) {
            $this->removeFromGameOverCountArray($x, $y);
            $status = 3;
        } elseif ($this->matrix[$y][$x] == 1) {
            $status = 2;
        }
        return $status;
    }

    /**
     * @return bool
     */
    public function isOver()
    {
        return !count($this->gameOverCountArray);
    }
}
